import io from 'socket.io-client'
import bus from '@/utils/mitt';
const token = localStorage.getItem('t')
const name = localStorage.getItem('u')
import { createDiscreteApi } from 'naive-ui'
const { message } = createDiscreteApi(['message'])
// 链接 服务端
const socket = io(import.meta.env.VITE_SOCKET_URL, {
    query: {},
    transports: ['websocket', 'polling'],
    autoConnect: true,
    reconnection: true,
    reconnectionAttempts: 8,
    reconnectionDelay: 5000,
    reconnectionDelayMax: 10000,
})

// 错误
socket.on('error', (error) => {
    message.error('error' + error);
})

// 重新尝试连接
socket.on('reconnect_attempt', (attemptNumber) => {
    message.error('重新尝试连接' + attemptNumber);
})
//重新连接错误
socket.on('reconnect_error', (error) => {
    message.error('重新连接错误' + error);
})

// 重新连接
socket.on('reconnect', () => {
    message.success('重新连接')
})

socket.on('reconnect_failed', () => {
    message.error('重新连接失败')
})
socket.on('ping', () => {
    message.info('ping')
})

let timer: any = null;
function init() {
    if (token) {
        socket.id = token;
        const user = {
            id: token,
            name: name,
            imageUrl: localStorage.getItem('avatar'),
            messageLen: 0, // 未读消息
            view: false, // 监听用户是否打开窗口
        }

        socket.on("connect", () => {
            socket.emit("events", user);
            // 简易心跳
            timer && clearInterval(timer);
            timer = setInterval(() => {
                socket.send('heartbeat');
                console.log('heartbeat');
            }, 10000)
        });

        socket.on('gropUser', (user) => {
            bus.emit('current-gropUser', user);
        })

        // 私聊
        socket.on('personalSend', (user) => {
            bus.emit('private-message', user)
        })


        // 告知用户已读通知未读用户
        socket.on('read-reolad', (type) => {
            bus.emit('read-reolad-message', type);
        })

        //获取聊天记录
        socket.on('ChatHistory', (userChatHistoryData) => {
            bus.emit('chat-history', userChatHistoryData ?? [])
        })
        // 获取群聊记录
        socket.on('GroupChatHistory', (userChatHistoryData) => {
            bus.emit('group-chat-history', userChatHistoryData ?? [])
        })

        socket.on("disconnect", () => {
            clearInterval(timer);
            setTimeout(() => {
                message.error('尝试重新连接。。。')
                socket.connect();
            }, 5000); // 这里的5000是重连的间隔时间，可以根据需要调整
            socket.emit("on_close", user);
            bus.emit("disconnect-warning");
        })
    }
}


function groupMessage(message: any) {
    socket.emit('group', message)
}

// 私
function personalMessage(user: any, userId: string) {
    socket.emit('personal', { user, userId })
}

//聊天记录查询
function privateChatHistory(userName: string) {
    socket.emit('queryMessage', userName)
}

// 群聊记录
function groupChatHistory() {
    socket.emit('queryGroupMessage', 'groupMessageList');
}

// 删除聊天记录
function deleteChatHistory(userName: string) {
    socket.emit('deleteMessage', userName)
}

// 设置已读
function setCurrentMessageToRead(user: any, userId: string) {
    socket.emit('setReadMessage', { ...user, userId });
}

type MessageType = 'group' | 'private';
//消息撤回
function revokeMessage(key: any, messageId: string, type: MessageType) {
    if (type === 'group') {
        socket.emit('revoke-group-message', key, messageId);
        return;
    }
    socket.emit('revoke-private-message', key, messageId);
}

// 关闭窗口
function privateCloseWindow(userName: string) {
    socket.emit('closeWindow', userName);
}


function close() {
    socket.emit('on_close', { id: token, name: name });
}

function handleConnect() {
    if (token) {
        socket.on('currentUserCount', (e) => {
            bus.emit('userCount', e);

        })

        socket.on('groupMessage', (e) => {
            bus.emit('group-message', e)
        })

    }
}



export {
    init,
    close,
    revokeMessage,
    handleConnect,
    groupMessage,
    personalMessage,
    privateChatHistory,
    groupChatHistory,
    deleteChatHistory,
    setCurrentMessageToRead,
    privateCloseWindow
}